<template>
    <div>
        <div> <!-- 添加分类 -->
            <n-space>
                <n-button type="success" ghost @click="showAddModal = true">新增分类</n-button>
            </n-space>
            <n-modal v-model:show="showAddModal" :mask-closable="false" preset="dialog">
                <template #header>
                    <div>新增分类</div>
                </template>
                <div>
                    <n-input type="text" placeholder="请输入分类" clearable :allow-input="noSideSpace"
                        v-model:value="addCategoryInfo.name" />
                </div>
                <template #action>
                    <n-space>
                        <n-button type="success" @click="addCategory">提交</n-button>
                    </n-space>
                </template>
            </n-modal>
        </div>
        <div> <!-- 修改分类 -->
            <n-modal v-model:show="showUpdateModal" :mask-closable="false" preset="dialog">
                <template #header>
                    <div>修改分类</div>
                </template>
                <div>
                    <n-input type="text" placeholder="请输入分类" clearable :allow-input="noSideSpace"
                        v-model:value="updateCategoryInfo.name" />
                </div>
                <template #action>
                    <n-space>
                        <n-button type="success" @click="updateCategory">提交</n-button>
                    </n-space>
                </template>
            </n-modal>
        </div>
        <div> <!-- 数据表格 -->
            <n-data-table :columns="columns" :data="categoryList" :pagination="pagination" :bordered="false"
                :single-line="false" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted, h } from "vue";
import { useRouter, useRoute } from "vue-router";
import { NButton } from "naive-ui";
import { AdminStore } from "../../stores/AdminStore";

const router = useRouter()
const route = useRoute()

const axios = inject('axios')
const message = inject('message')
const dialog = inject('dialog')

const adminStore = AdminStore()

const showAddModal = ref(false); // 显示add模态框
const addCategoryInfo = reactive({ name: "" }) // 要提交的分类名
const showUpdateModal = ref(false); // 显示update模态框
const updateCategoryInfo = reactive({ name: "" }) // 要更新的分类名
const categoryList = ref([]) // 存储获取的分类列表

// 挂载时
onMounted(() => {
    loadDatas() // 获取数据
})

// 操作按钮
const actionsArr = [
    {
        title: '修改',
        key: 'updateCategory',
        type: 'success'
    },
    {
        title: '删除',
        key: 'deleteCategory',
        type: 'error'
    }
]
// 表格配置
const columns = [
    {
        title: "编号",
        key: "id",
        sorter: 'default',
        align: 'center'
    },
    {
        title: "名称",
        key: "name",
        align: 'center'
    },
    {
        title: "操作",
        align: 'center',
        render(row) {
            const buttonGroup = actionsArr.map((item) => {
                return h(
                    NButton,
                    {
                        strong: true,
                        size: 'small',
                        type: item.type,
                        onClick: () => {
                            if (item.key === 'updateCategory') {
                                // updateCategory(row)
                                updateModal(row)
                            } else {
                                // deleteCategory(row)
                                showDeleteDialog(row)
                            }
                        }
                    },
                    { default: () => item.title }
                )
            })
            return h('span', { class: 'but-group-space-evenly' }, buttonGroup)
        }
    }
];
// 定义分页配置
const pagination = {
    pageSize: 5
};

const loadDatas = async () => {
    try {
        let res = await axios.get("/api/category/list")
        console.log(res.data._dbres);
        categoryList.value = res.data._dbres
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
}
console.log(categoryList);

// 点击操作按钮
// update
// --------------------------------
const updateModal = (row) => {
    // console.log(row);
    showUpdateModal.value = true
    updateCategoryInfo.id = row.id
    updateCategoryInfo.name = row.name
}
const updateCategory = async () => {
    try {
        let res = await axios.post('/api/category/_token/update', { id: updateCategoryInfo.id, name: updateCategoryInfo.name })
        console.log(res);
        loadDatas()
        message.success(res.data.msg);
        showUpdateModal.value = false
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
};
// --------------------------------

// delete
// --------------------------------
const showDeleteDialog = (row) => {
    // console.log(row);
    dialog.warning({
        title: "警告",
        content: "是否要删除",
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
            deleteCategory(row)
        },
        onNegativeClick: () => { }
    });
}
const deleteCategory = async (row) => {
    try {
        let res = await axios.post('/api/category/_token/delete', { id: row.id })
        console.log(res);
        loadDatas()
        message.success(res.data.msg);
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
};
// --------------------------------

// add 模态框
// --------------------------------
const addCategory = async () => { // 提交
    try {
        let res = await axios.post('/api/category/_token/add', { name: addCategoryInfo.name })
        console.log(res);
        loadDatas()
        message.success(res.data.msg);
        showAddModal.value = false;
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
}
// --------------------------------

// 模态框 输入框验证
const noSideSpace = (value) => !value.startsWith(" ") && !value.endsWith(" ")

</script>

<style lang="scss" scoped></style>